<template>
  <div class="" style="padding: 0 15px 0 15px">
    <div class="user-layout">
      <!-- 左侧树形控件 -->
      <div class="tree-container">
        <div class="tree-header">
          <h3>客户列表</h3>
          <el-button type="primary" size="small" @click="addUser()">
            <el-icon>
              <Plus />
            </el-icon>
            新增客户
          </el-button>
        </div>
        <div style="height: 760px">
          <el-tree
            ref="userNameRef"
            style="height: 100%; padding-top: 10px"
            :data="userTreeData"
            :props="userProps"
            node-key="id"
            :default-expand-all="true"
            :expand-on-click-node="false"
            :highlight-current="true"
            class="user-tree"
            @node-click="userNodeClick"
          >
            <template #default="{ node, data }">
              <span class="tree-node">
                <el-icon class="tree-icon">
                  <UserFilled color="#409eff" />
                </el-icon>
                <span class="tree-label">{{ data.name }}</span>
                <span class="tree-count">{{ data.count || "0" }}</span>
              </span>
            </template>
          </el-tree>
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="content-container">
        <!-- 面包屑导航 -->
        <div class="breadcrumb-container">
          <el-breadcrumb separator=">">
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item v-if="currentCategory">
              {{ currentCategory.label }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <!-- 搜索区域 -->
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" class="search-form">
            <el-form-item label="客户名称" prop="name">
              <el-input
                v-model="queryParams.name"
                placeholder="请输入客户名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="账号" prop="userName">
              <el-input
                v-model="queryParams.userName"
                placeholder="请输入账号"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="客户类型" prop="userType">
              <el-select
                v-model="queryParams.userType"
                placeholder="请选择客户类型"
                style="width: 240px"
              >
                <el-option
                  v-for="item in userTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="isUnder" label="包含下级" @change="isUnderEvent" />
            </el-form-item>
            <el-form-item class="search-buttons">
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 操作按钮区域 -->
        <div class="action-container">
          <div
            style="display: flex; justify-content: space-between; align-items: center; width: 100%"
          >
            <div style="flex: 1">
              <el-button type="primary" @click="addUser()">新增</el-button>
            </div>
            <div>
              <div class="data-table__toolbar" style="position: relative">
                <div
                  style="display: flex; align-items: center"
                  class="moreBtn"
                  @click="isShowBoxChange"
                >
                  <!-- <el-image style="width: 20px; height: 20px" :src="moreSrc" :fit="fit" /> -->

                  <el-icon :size="20" color="#88898c" style="margin-right: 5px">
                    <Operation />
                  </el-icon>
                  <!-- <span>列设置</span> -->
                  <el-icon color="#88898c">
                    <CaretBottom />
                  </el-icon>
                </div>
                <div v-if="isShowBox" class="selectBox">
                  <el-checkbox-group v-model="isTableShow" @change="checkBoxChange">
                    <el-row>
                      <el-col :span="8">
                        <el-checkbox label="序号" :value="'序号'" />
                      </el-col>
                      <el-col :span="8">
                        <el-checkbox label="客户名称" :value="'客户名称'" />
                      </el-col>
                      <el-col :span="8">
                        <el-checkbox label="账号" :value="'账号'" />
                      </el-col>
                      <el-col :span="8">
                        <el-checkbox label="客户类型" :value="'客户类型'" />
                      </el-col>
                      <el-col :span="8">
                        <el-checkbox label="客户编码" :value="'客户编码'" />
                      </el-col>
                      <el-col :span="8">
                        <el-checkbox label="排序" :value="'排序'" />
                      </el-col>
                      <el-col :span="8">
                        <el-checkbox label="客户状态" :value="'客户状态'" />
                      </el-col>
                      <el-col :span="8">
                        <el-checkbox label="备注" :value="'备注'" />
                      </el-col>
                      <el-col :span="8">
                        <el-checkbox label="联系人" :value="'联系人'" />
                      </el-col>
                      <el-col :span="8">
                        <el-checkbox label="联系电话" :value="'联系电话'" />
                      </el-col>
                      <el-col :span="8">
                        <el-checkbox label="邮箱" :value="'邮箱'" />
                      </el-col>
                      <el-col :span="8">
                        <el-checkbox label="创建时间" :value="'创建时间'" />
                      </el-col>
                      <el-col :span="8">
                        <el-checkbox label="到期时间" :value="'到期时间'" />
                      </el-col>
                    </el-row>
                  </el-checkbox-group>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 用户表格 -->
        <div class="table-container">
          <el-card shadow="hover" class="">
            <el-table
              ref="userTableRef"
              v-loading="loading"
              style="height: 485px; width: 100%"
              :data="userTableList"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column v-if="isTableShow.includes('序号')" type="index" width="60" />
              <el-table-column
                v-if="isTableShow.includes('客户名称')"
                label="客户名称"
                align="center"
                width="200"
                prop="name"
              />
              <el-table-column
                v-if="isTableShow.includes('账号')"
                label="账号"
                align="center"
                width="200"
                prop="userName"
              />
              <el-table-column
                v-if="isTableShow.includes('客户类型')"
                label="客户类型"
                align="center"
                width="120"
              >
                <template #default="scope">
                  <el-tag v-if="scope.row.userType === 1" type="warning">管理员</el-tag>
                  <el-tag v-if="scope.row.userType === 2" type="warning">代理商</el-tag>
                  <el-tag v-if="scope.row.userType === 3" type="warning">机构</el-tag>
                </template>
              </el-table-column>

              <el-table-column
                v-if="isTableShow.includes('客户状态')"
                label="客户状态"
                align="center"
                width="120"
              >
                <template #default="scope">
                  <el-tag v-if="scope.row.status === 0" type="success">正常</el-tag>
                  <el-tag v-else type="info">停用</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                v-if="isTableShow.includes('排序')"
                label="排序"
                width="100"
                align="center"
                prop="sort"
              />
              <el-table-column
                v-if="isTableShow.includes('客户编码')"
                label="客户编码"
                align="center"
                width="100"
                prop="userCode"
              />
              <el-table-column
                v-if="isTableShow.includes('联系人')"
                label="联系人"
                align="center"
                width="100"
                prop="sysUserContacts[0].contact"
              />
              <el-table-column
                v-if="isTableShow.includes('联系电话')"
                label="联系电话"
                align="center"
                width="110"
                prop="sysUserContacts[0].contactNumber"
              />
              <el-table-column
                v-if="isTableShow.includes('邮箱')"
                label="邮箱"
                align="center"
                width="110"
                prop="sysUserContacts[0].contactEmail"
              />
              <el-table-column
                v-if="isTableShow.includes('创建时间')"
                label="创建时间"
                width="230"
                align="center"
                prop="creationTime"
              />
              <el-table-column
                v-if="isTableShow.includes('到期时间')"
                label="到期时间"
                width="170"
                align="center"
                prop="expirationTime"
              />
              <el-table-column
                v-if="isTableShow.includes('备注')"
                label="备注"
                width="170"
                align="center"
                prop="remark"
              />
              <el-table-column fixed="right" align="center" label="操作" width="320">
                <template #default="scope">
                  <el-button
                    v-hasPerm="['system:user:add']"
                    type="primary"
                    link
                    size="small"
                    @click.stop="bindRolesEvent(scope.row)"
                  >
                    角色授权
                  </el-button>
                  <el-button
                    v-hasPerm="['system:user:add']"
                    type="primary"
                    link
                    size="small"
                    @click.stop="infoMengEvent(scope.row)"
                  >
                    车辆管理
                  </el-button>
                  <el-button
                    v-hasPerm="['system:menu:edit']"
                    type="primary"
                    link
                    size="small"
                    @click.stop="addUser(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    v-hasPerm="['system:menu:delete']"
                    type="danger"
                    link
                    size="small"
                    @click.stop="handleDelete(scope.row.id)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-if="total > 0"
              v-model:total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              style="float: right"
              @pagination="pageEvent"
            />
          </el-card>
        </div>
      </div>
    </div>
    <el-drawer
      v-model="infoDialog"
      :close-on-click-modal="false"
      title="车辆管理"
      width="40%"
      draggable
      @close="vehDialogClose"
    >
      <div style="height: 530px">
        <el-button type="success" icon="plus" @click="addCarInfo">新增</el-button>

        <el-table
          ref="infoTableRef"
          v-loading="loading"
          style="height: 450px; width: 100%; margin-top: 20px"
          :data="infoTableList"
        >
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <el-table-column type="index" width="60" />
          <el-table-column label="车牌号" align="center" width="100" prop="carNumber" />
          <el-table-column label="司机名称" align="center" prop="driverName" />
          <el-table-column label="电话" align="center" prop="phone" />
          <el-table-column fixed="right" align="center" label="操作" width="200">
            <template #default="scope">
              <el-button type="primary" link size="small" @click.stop="addCarInfo(scope.row)">
                编辑
              </el-button>
              <el-button
                v-if="scope.row?.deviceId"
                type="primary"
                link
                size="small"
                @click.stop="unbindDevEvent(scope.row)"
              >
                解绑设备
              </el-button>
              <el-button
                v-else
                type="primary"
                link
                size="small"
                @click.stop="bindDevEvent(scope.row)"
              >
                绑定设备
              </el-button>
              <el-button type="danger" link size="small" @click.stop="delCarInfo(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div>
          <pagination
            v-if="total1 > 0"
            v-model:total="total1"
            v-model:page="queryParams1.pageNum"
            v-model:limit="queryParams1.pageSize"
            style="float: right"
            @pagination="pageEvent"
          />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="roleSubmit">确 定</el-button> -->
          <el-button @click="infoDialog = false">取 消</el-button>
        </div>
      </template>
    </el-drawer>

    <el-dialog
      v-model="roleDialog"
      :close-on-click-modal="false"
      title="角色授权"
      width="30%"
      draggable
      @close="roleDialogClose"
    >
      <el-form ref="roleFormRef" :model="roleFormData" :rules="roleRules" label-width="100px">
        <el-form-item label="" prop="roleSelect">
          <el-select v-model="roleFormData.roleSelect" multiple placeholder="请选择授权的角色">
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="roleSubmit">确 定</el-button>
          <el-button @click="roleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="addVehDialog"
      :close-on-click-modal="false"
      :title="vehtitle"
      width="60%"
      draggable
      @close="addVehDialogClose"
    >
      <el-form ref="infoFormRef" :model="vehicleData" :rules="vehicleRules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="车牌号" prop="carNumber">
              <el-input v-model="vehicleData.carNumber" placeholder="请输入车牌号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="司机名称" prop="driverName">
              <el-input v-model="vehicleData.driverName" placeholder="请输入司机名称"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="vehicleData.phone" placeholder="请输入电话"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="身份证号" prop="cardId">
              <el-input v-model="vehicleData.cardId" placeholder="请输身份证号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="sn码" prop="sn">
              <el-input v-model="vehicleData.sn" placeholder="请输入sn码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车架号" prop="carRack">
              <el-input v-model="vehicleData.carRack" placeholder="请输入车架号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发动机号" prop="engine">
              <el-input v-model="vehicleData.engine" placeholder="请输入发动机号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总里程" prop="totalMileage">
              <div style="display: flex; align-items: center">
                <el-input v-model="vehicleData.totalMileage" placeholder="请输入总里程"></el-input>
                <spna style="margin-left: 10px; width: 100px">公里</spna>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车辆颜色" prop="carColor">
              <el-input v-model="vehicleData.carColor" placeholder="请输入车辆颜色"></el-input>
            </el-form-item>
          </el-col>
          <el-col v-if="isShow" :span="8">
            <el-form-item label="设备" prop="deviceName">
              <el-input
                v-model="vehicleData.deviceName"
                disabled
                placeholder="请选择设备"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col v-if="isShow" :span="24" style="margin-top: 20px">
            <div style="width: 300px">
              <el-input
                v-model="IMEI"
                placeholder="请输入IMEI,回车搜索"
                @keyup.enter="handleQuery1"
              >
                <template #append>
                  <el-button :icon="Search" @click="handleQuery1" />
                </template>
              </el-input>
            </div>
            <el-table
              ref="devTableRef"
              v-loading="loading1"
              :data="devData"
              highlight-current-row
              style="width: 100%; height: 260px; margin-top: 10px"
              @current-change="devEventChange"
            >
              <el-table-column label="IMEI" align="center" prop="deviceNumber" />
              <el-table-column label="设备名称" align="center" prop="deviceName" />
              <el-table-column label="设备SIM卡号" align="center" prop="sim" />
              <el-table-column label="设备类型" align="center">
                <template #default="scope">
                  <!-- 根据设备类型ID匹配显示对应的设备类型名称 -->
                  {{
                    devTypeList.find((type) => type.id == parseInt(scope.row.deviceType))
                      ?.typeName || "-"
                  }}
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-if="total2 > 0"
              v-model:total="total2"
              v-model:page="queryParams2.pageNum"
              v-model:limit="queryParams2.pageSize"
              style="float: right; height: 50px"
              @pagination="pageEvent2"
            />
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addVehInfoEvent">确 定</el-button>
          <el-button @click="addVehDialogClose">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="bindDevValue"
      :close-on-click-modal="false"
      :title="'绑定设备'"
      width="60%"
      draggable
      @close="CloseBindDevDialog"
    >
      <div style="height: 520px">
        <div style="display: flex; align-items: center; width: 100%">
          <div style="flex: 1">
            <el-input
              v-model="devname"
              style="width: 300px"
              disabled
              placeholder="请选择设备"
            ></el-input>
          </div>
          <div style="width: 300px">
            <el-input v-model="IMEI" placeholder="请输入IMEI,回车搜索" @keyup.enter="handleQuery1">
              <template #append>
                <el-button :icon="Search" @click="handleQuery1" />
              </template>
            </el-input>
          </div>
        </div>

        <el-table
          ref="devTableRef"
          v-loading="loading1"
          :data="devData"
          highlight-current-row
          style="width: 100%; height: 420px; margin-top: 20px"
          @current-change="devEventChange"
        >
          <el-table-column label="IMEI" align="center" prop="deviceNumber" />
          <el-table-column label="设备名称" align="center" prop="deviceName" />
          <el-table-column label="设备SIM卡号" align="center" prop="sim" />
          <el-table-column label="设备类型" align="center">
            <template #default="scope">
              <!-- 根据设备类型ID匹配显示对应的设备类型名称 -->
              {{
                devTypeList.find((type) => type.id == parseInt(scope.row.deviceType))?.typeName ||
                "-"
              }}
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-if="total2 > 0"
          v-model:total="total2"
          v-model:page="queryParams2.pageNum"
          v-model:limit="queryParams2.pageSize"
          style="float: right; height: 50px"
          @pagination="pageEvent2"
        />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="bindDev">绑 定</el-button>
          <el-button @click="CloseBindDevDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialog.visible"
      :close-on-click-modal="false"
      :title="dialog.title"
      width="60%"
      draggable
      @close="handleCloseDialog"
    >
      <el-row>
        <el-col :span="16">
          <el-form ref="menuFormRef" :model="formData" :rules="rules" label-width="100px">
            <el-form-item label="上级客户">
              <el-input v-model="pUserName" disabled></el-input>
            </el-form-item>

            <el-row>
              <el-col :span="24">
                <el-form-item label="客户名称" prop="name">
                  <el-input v-model="formData.name" placeholder="请输入客户名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="账号" prop="userName">
                  <el-input v-model="formData.userName" placeholder="请输入账号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="密码" prop="passWord">
                  <el-input
                    v-model="formData.passWord"
                    type="password"
                    show-password
                    placeholder="请输入密码"
                  ></el-input>
                  <div style="font-size: 12px; color: #303133">初始密码：888888</div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="客户类型" prop="userType">
                  <el-radio-group v-model="formData.userType" @change="handleMenuTypeChange">
                    <el-radio size="default" :value="1">管理员</el-radio>
                    <el-radio size="default" :value="2">代理商</el-radio>
                    <el-radio size="default" :value="3">机构</el-radio>
                    <!-- <el-radio :value="MenuTypeEnum.EXTLINK">外链</el-radio> -->
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户编码" prop="userCode">
                  <el-input v-model="formData.userCode" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排序" prop="sort">
                  <el-input-number
                    v-model="formData.sort"
                    :min="0"
                    :max="999"
                    @change="handleChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否启用">
                  <el-switch
                    v-model="userStatus"
                    inline-prompt
                    active-text="是"
                    inactive-text="否"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="联系人" prop="sysUserContacts[0].contact">
                  <el-input
                    v-model="formData.sysUserContacts[0].contact"
                    placeholder="请输入联系人"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="sysUserContacts[0].contactNumber">
                  <el-input
                    v-model="formData.sysUserContacts[0].contactNumber"
                    placeholder="请输入联系电话"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="邮箱" prop="sysUserContacts[0].contactEmail">
                  <el-input
                    v-model="formData.sysUserContacts[0].contactEmail"
                    placeholder="请输入邮箱"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                placeholder="请输入备注说明"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8">
          <div
            style="
              border: #dcdfe6 1px solid;
              padding: 15px;
              margin-left: 10px;
              height: 500px;
              overflow-y: auto;
            "
          >
            <el-input
              v-model="userNameQueryValue"
              style="max-width: 600px"
              placeholder="请输入客户名称"
              class="input-with-select"
            ></el-input>
            <el-tree
              ref="userNameRef"
              style="width: 100%; margin-top: 10px"
              :data="userTreeData"
              :props="userProps"
              highlight-current
              :expand-on-click-node="false"
              :current-node-key="defaultSelectedId"
              :default-expanded-keys="expandedKeys"
              :filter-node-method="filterNode"
              node-key="id"
              @node-click="userNodeClick1"
            ></el-tree>
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useAppStore } from "@/store/modules/app.store";
import { DeviceEnum } from "@/enums/settings/device.enum";
import moreSrc from "@/assets/more.png";
import DeviceAPI from "@/api/system/device.api";
import { Search, Plus, Document } from "@element-plus/icons-vue";
import MenuAPI, { MenuQuery, MenuForm, MenuVO } from "@/api/system/menu.api";
import UserAPI from "@/api/system/user.api";
import more from "@/assets/more.png";
import type { FilterNodeMethodFunction, TreeInstance } from "element-plus";
import { MenuTypeEnum } from "@/enums/system/menu.enum";
import { ElStep, spaceItemProps } from "element-plus";
import RoleAPI from "@/api/system/role.api";
import { log } from "console";
import VehicleAPI from "@/api/system/vehicle.api";

defineOptions({
  name: "SysMenu",
  inheritAttrs: false,
});
const vehid = ref(undefined);
const IMEI = ref("");
const devname = ref("");
const devid = ref(undefined);
const bindDevValue = ref(false);
const vehtitle = ref("");
const devData = ref([]);
const loading1 = ref(false);
const infoTableList = ref([]);
const infoList = ref([]);
const bindRolesUserId = ref(undefined);
const userStatus = ref(true);
const total = ref(0);
const total2 = ref(0);
const isShow = ref(true);
const total1 = ref(0);
const addVehDialog = ref(false);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  userPid: 1,
  name: "",
  userName: "",
  userType: 0,
  isUnder: "true",
});
const queryParams1 = ref({
  pageNum: 1,
  pageSize: 10,
  isLower: true,
  userId: undefined,
  clientName: "",
  cardId: "",
});
const devTableRef = ref(null);
const queryParams2 = ref({
  pageNum: 1,
  pageSize: 10,
  deviceNumber: "",
});
const infoDialog = ref(false);
const isShowBox = ref(false);
const isTableShow = ref([
  "序号",
  "客户名称",
  "账号",
  "客户类型",
  "客户状态",
  "联系人",
  "联系电话",
  "创建时间",
]);
const roleOptions = ref([]);
const roleDialog = ref(false);
const roleFormData = ref({
  roleSelect: [],
});
const userTypeList = ref([
  {
    value: 0,
    label: "全部",
  },
  {
    value: 1,
    label: "管理员",
  },
  {
    value: 2,
    label: "代理商",
  },
  {
    value: 3,
    label: "机构",
  },
]);
function CloseBindDevDialog() {
  bindDevValue.value = false;
}
const isShowInfoDialog = ref(false);

const addVehInfoEvent = async () => {
  if (vehicleData.value.id) {
    await UserAPI.updateVehicle(vehicleData.value);
    ElMessage.success("修改成功");
  } else {
    await UserAPI.addVehicle(vehicleData.value);
    ElMessage.success("新增成功");
  }
  getVehList();
  addVehDialog.value = false;
};
const devTypeList = ref([]);
const devType = ref({
  typeName: "",
});

const getDevType1 = async () => {
  const res = await DeviceAPI.getdevType(devType.value);
  devTypeList.value = res.data.data;
};

const infoFormRef = ref(null);
const vehicleData = ref({
  id: undefined,
  userId: undefined,
  driverName: "",
  phone: "",
  carNumber: "",
  carColor: "",
  cardId: "",
  sn: "",
  carRack: "",
  engine: "",
  totalMileage: 0,
  deviceName: "",
  deviceId: "",
});
const defaultSelectedId = ref(1);
const userTreeData = ref([]);
const userProps = {
  children: "children",
  label: "name",
};
const unbindform = ref({
  id: undefined,
});

const userTableRef = ref(null);
const appStore = useAppStore();
const userTableList = ref([]);
const queryFormRef = ref();
const menuFormRef = ref();
const parentData = ref({});
const userNameQueryValue = ref("");
const loading = ref(false);
const isUnder = ref(true);
const dialog = reactive({
  title: "新增菜单",
  visible: false,
});
const expandedKeys = ref([]);
const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));
// 菜单表格数据
const menuTableData = ref<MenuVO[]>([]);
// 顶级菜单下拉选项
const menuOptions = ref<OptionType[]>([]);

const userNameRef = ref(null);
// 初始菜单表单数据
const pUserName = ref("");
const currentCategory = ref(null);
const formData = ref<MenuForm>({
  id: undefined,
  name: "",
  userName: "",
  passWord: "888888",
  userType: 1,
  userCode: "",
  sort: 0,
  status: true,
  remark: "",
  userPid: undefined,
  sysUserContacts: [
    {
      id: undefined,
      contact: "",
      contactNumber: "",
      contactEmail: "",
      userId: undefined,
    },
  ],
  sysUserExpands: [
    {
      id: undefined,
      address: "",
      creditCode: "",
      profile: "",
      userId: undefined,
    },
  ],
});

function delCarInfo(row) {
  console.log(row);
  ElMessageBox.confirm("确认删除已选中的设备?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      VehicleAPI.deleteByIds(row.id)
        .then(() => {
          ElMessage.success("删除成功");
          getVehList();
        })
        .finally(() => {
          loading.value = false;
        });
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}
// 绑定设备
function bindDevEvent(row) {
  console.log(row);
  vehid.value = row.id;
  getDeviceList();
  bindDevValue.value = true;
}

// 确定绑定设备
async function bindDev() {
  if (devid.value == undefined) {
    ElMessage.error("请选择设备");
    return;
  }

  await UserAPI.bind({
    id: vehid.value,
    deviceId: devid.value,
  });
  getVehList();
  ElMessage.success("绑定成功");
  bindDevValue.value = false;
}
// 清空车辆信息
function clearCarInfo() {
  vehicleData.value.id = undefined;
  vehicleData.value.driverName = "";
  vehicleData.value.phone = "";
  vehicleData.value.carNumber = "";
  vehicleData.value.sn = "";
  vehicleData.value.cardId = "";
  vehicleData.value.carRack = "";
  vehicleData.value.engine = "";
  vehicleData.value.totalMileage = 0;
  vehicleData.value.carColor = "";
}

// 车辆信息新增、编辑
function addCarInfo(row?) {
  clearCarInfo();
  console.log(row);

  if (row?.id) {
    // vehicleData.value.carNumber = row?.carNumber
    vehicleData.value.id = row?.id;
    vehicleData.value.driverName = row?.driverName;
    vehicleData.value.phone = row?.phone;
    vehicleData.value.carNumber = row?.carNumber;
    vehicleData.value.sn = row?.sn;
    vehicleData.value.cardId = row?.cardId;
    vehicleData.value.engine = row?.engine;
    vehicleData.value.totalMileage = row?.totalMileage;
    vehicleData.value.carColor = row?.carColor;
    vehtitle.value = "编辑车辆";
    isShow.value = false;
  } else {
    vehtitle.value = "新增车辆";
    isShow.value = true;
  }

  getDeviceList();
  addVehDialog.value = true;
}

function devEventChange(val) {
  console.log("表格", val);
  if (val) {
    if (addVehDialog.value) {
      vehicleData.value.deviceId = val.id;
      vehicleData.value.deviceName = val.deviceName;
    }
    if (bindDevValue.value) {
      devname.value = val.deviceName;
      devid.value = val.id;
    }
  }
}

function handleQuery1() {
  // 清除表格选中状态
  devTableRef.value?.setCurrentRow();
  // 清空选中的设备信息
  vehicleData.value.deviceId = "";
  vehicleData.value.deviceName = "";

  if (IMEI.value == "") {
    queryParams2.value.deviceNumber = "";
  } else {
    queryParams2.value.deviceNumber = IMEI.value;
  }

  getDeviceList();
}

// 车辆管理新增、编辑关闭
function vehDialogClose() {
  isShowInfoDialog.value = false;
}

function checkBoxChange(val) {
  console.log(val);
  isTableShow.value = val;
}

function roleDialogClose() {
  roleDialog.value = false;
}
// 菜单表单数据
// const formData = ref({ ...initialMenuFormData.value });
// 表单验证规则
const roleRules = reactive({
  // pUserName: [{ required: true, message: "请选择上级客户", trigger: "blur" }],
});
const rules = reactive({
  pUserName: [{ required: true, message: "请选择上级客户", trigger: "blur" }],
  name: [{ required: true, message: "输入公司名称", trigger: "blur" }],
  userName: [{ required: true, message: "请输入账号", trigger: "blur" }],
  passWord: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

const vehicleRules = reactive({
  // driverName: [{ required: true, message: "请输入司机姓名", trigger: "blur" }],
  carNumber: [{ required: true, message: "请输入车牌号", trigger: "blur" }],
});

async function getDeviceList() {
  loading1.value = true;
  const { data } = await DeviceAPI.notBind(queryParams2.value);
  console.log(data);
  total2.value = parseInt(data.data.total);
  devData.value = data.data.records;
  loading1.value = false;
}
function isShowBoxChange() {
  isShowBox.value = !isShowBox.value;
}
// 选择表格的行菜单ID
const selectedMenuId = ref<string | undefined>();
const filterNode: FilterNodeMethodFunction = (value: string, data: Tree) => {
  if (!value) return true;
  console.log(data, value);
  return data.userName.includes(value);
};
function bindRolesEvent(row) {
  bindRolesUserId.value = row.id;
  console.log("sssssddd", bindRolesUserId.value);
  getRole(row.id);
  getRoleList();
}
function addVehDialogClose() {
  devname.value = "";
  devid.value = undefined;
  addVehDialog.value = false;
}
async function infoMengEvent(row) {
  vehicleData.value.userId = row.id;

  console.log("deewe", vehicleData.value.userId, row);
  getDevType1();
  queryParams1.value.userId = row.id;
  getVehList();
  infoDialog.value = true;
}
async function getVehList() {
  await UserAPI.pageList(queryParams1.value).then((res) => {
    console.log(res);
    infoTableList.value = res.data.data.records;
    total1.value = parseInt(res.data.data.total);
  });
}
async function getRole(userId) {
  const id = {
    id: userId,
  };
  await RoleAPI.getRoles(id).then((res) => {
    console.log("拥有的角色", res);
    if (res.data.code == 0) {
      roleFormData.value.roleSelect = [];
      res.data.data.forEach((res) => {
        roleFormData.value.roleSelect.push(res.id);
      });
    } else if (res.data.code == 1) {
      ElMessage.error("该用户未分配角色");
      roleFormData.value.roleSelect = [];
    }
  });
}

function roleCloseDialog() {
  roleDialog.value = false;
}

function roleSubmit() {
  if (roleFormData.value.roleSelect.length > 0) {
    const id = {
      userId: bindRolesUserId.value,
      roles: roleFormData.value.roleSelect,
    };

    console.log("角色分配", id);
    RoleAPI.bindRoles(id).then((res) => {
      console.log("ssss", res);
      ElMessage.success("角色分配成功");
      roleDialog.value = false;
    });
  } else {
    ElMessage.success("角色");
  }
}

async function getRoleList() {
  const page = {
    pageNum: 1,
    pageSize: 10,
    roleName: "",
  };
  await RoleAPI.getPage(page).then((res) => {
    console.log("用户角色", res);
    roleOptions.value = res.data.data;
    roleDialog.value = true;
  });
}
function addUser(row) {
  if (row?.id) {
    console.log(row);
    dialog.title = "编辑用户";
    formData.value.id = row?.id;
    formData.value.name = row?.name;
    formData.value.userType = row?.userType;
    formData.value.userName = row?.userName;
    formData.value.sort = row?.sort;
    if (row?.status == 0) {
      formData.value.status = true;
    } else {
      formData.value.status = false;
    }
    formData.value.userPid = row?.userPid;
    formData.value.remark = row?.remark;
    formData.value.userCode = row?.userCode;
    formData.value.sysUserContacts[0].contact = row?.sysUserContacts[0]?.contact;
    formData.value.sysUserContacts[0].contactNumber = row?.sysUserContacts[0]?.contactNumber;
    formData.value.sysUserContacts[0].contactEmail = row?.sysUserContacts[0]?.contactEmail;

    if (row?.sysUserContacts[0]?.userId) {
      formData.value.sysUserContacts[0].userId = row?.sysUserContacts[0]?.userId;
    } else {
      formData.value.sysUserContacts[0].userId = row?.id;
    }
    formData.value.sysUserContacts[0].id = row?.sysUserContacts[0]?.id;

    defaultSelectedId.value = row?.userPid;
    pUserName.value = getLabelById(userTreeData.value, row?.userPid);
    // console.log("row", userTreeData.value, getLabelById(userTreeData.value, row?.userPid));
    dialog.visible = true;
  } else {
    dialog.visible = true;
    dialog.title = "新增用户";
    defaultSelectedId.value = parentData.value.id;
    pUserName.value = parentData.value.userName;
    formData.value.userPid = parentData.value.id;
    formData.value.userCode = getUserCode();
  }
}
function getLabelById(treeData, targetId) {
  // 遍历当前层级的节点
  console.log("获取节点", treeData, targetId);
  for (const node of treeData) {
    // 找到匹配的节点，返回其label
    if (node.id === targetId) {
      return node.userName;
    }
    // 若当前节点有子节点，递归查询子节点
    if (node.children && node.children.length > 0) {
      const result = getLabelById(node.children, targetId);
      // 子节点中找到匹配项，返回结果
      if (result !== null) {
        return result;
      }
    }
  }
  // 遍历完所有节点未找到匹配项
  return null;
}

function isUnderEvent(index) {
  console.log(index);
  if (index) {
    queryParams.value.isUnder = "true";
    queryParams1.value.isLower = true;
  } else {
    queryParams.value.isUnder = "false";
    queryParams1.value.isLower = false;
  }
}
async function getTreeData() {
  await UserAPI.getTreeInfo().then((data) => {
    userTreeData.value = data.data.data;
    collectExpandedIds(userTreeData.value);
    console.log("树形菜单", data.data.data[0]);
    parentData.value = data.data.data[0];
    queryParams.value.userPid = data.data.data[0].userPid;
    getUserList();
  });
}

// 页码切换
function pageEvent(val) {
  console.log("1111", val);
  queryParams.value.pageNum = val.page;
  queryParams.value.pageSize = val.limit;
  handleQuery();
}

// 设备页码切换
function pageEvent2(val) {
  queryParams2.value.pageNum = val.page;
  queryParams2.value.pageSize = val.limit;
}

function getUserCode() {
  const timestamp = Date.now();
  const random = Math.floor(Math.random() * 1000)
    .toString()
    .padStart(3, "0");
  return timestamp + random;
}

function collectExpandedIds(nodes) {
  nodes.forEach((node) => {
    if (node.children && node.children.length > 0) {
      expandedKeys.value.push(node.id);
      // 递归处理子节点
      collectExpandedIds(node.children);
    }
  });
}

function userNodeClick1(value) {
  console.log("node", value);
  pUserName.value = value.userName;
  formData.value.userPid = value.id;
}

function userNodeClick(value) {
  console.log(value);
  queryParams.value.userPid = value.id;
  getUserList();
  parentData.value = value;
}

// 查询用户分页表格数据
async function getUserList() {
  await UserAPI.getPage(queryParams.value).then((data) => {
    const res = data.data.data;
    userTableList.value = res.records;
    total.value = parseInt(res.total);
    console.log("分页表格数据", total.value);
  });
}

function userNameQuery() {}

// 查询菜单
function handleQuery() {
  loading.value = true;
  UserAPI.getPage(queryParams.value)
    .then((data) => {
      userTableList.value = data.data.data.records;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

// 行点击事件
function handleRowClick(row: MenuVO) {
  selectedMenuId.value = row.id;
}

const transformNode = (node) => {
  const transformed = {
    value: node.id.toString(),
    label: node.menuName,
    type: node.menuType,
  };
  const children = node.children;

  if (Array.isArray(children) && children.length > 0) {
    if (children) transformed.children = children.map((child) => transformNode(child)); // 递归处理子数组
  } else {
    transformed.children = []; // 统一处理为空数组（避免后续渲染报错）
  }
  return transformed;
};
/**
 * 递归过滤树形结构中 type 为 3 的节点
 * @param {Array} nodes - 当前层级的节点数组
 * @returns 过滤后的节点数组
 */
const filterTree = (nodes) => {
  // 1. 过滤当前层级：排除 type 为 3 的节点
  return (
    nodes
      .filter((node) => node.menuType !== 3)
      // 2. 递归处理子节点（如果有）
      .map((node) => {
        // 若当前节点有子节点，递归过滤子节点
        if (Array.isArray(node.children) && node.children.length > 0) {
          return {
            ...node, // 保留当前节点的其他属性
            children: filterTree(node.children), // 递归过滤子节点
          };
        }
        // 没有子节点或子节点为空，直接返回当前节点
        return node;
      })
  );
};

/**
 * 提交表单
 */
function handleSubmit() {
  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      if (userStatus.value) {
        formData.value.status = 0;
      } else {
        formData.value.status = 1;
      }
      const userId = formData.value.id;
      console.log("新增", formData.value);

      if (userId) {
        // if (formData.value.menuPid == menuId) {
        //   ElMessage.error("上级菜单不能为当前菜单");
        //   return;
        // }
        console.log("菜单", formData.value);

        UserAPI.update(formData.value).then(() => {
          if (formData.value.sysUserContacts[0]?.id) {
            console.log(111);

            UserAPI.updateContact(formData.value.sysUserContacts[0]).then(() => {
              ElMessage.success("修改成功");
              handleCloseDialog();
              handleQuery();
            });
          } else {
            console.log(222);
            UserAPI.addContact(formData.value.sysUserContacts[0]).then(() => {
              ElMessage.success("修改成功");
              handleCloseDialog();
              handleQuery();
            });
          }
        });
      } else {
        console.log("新增成功", formData.value);
        UserAPI.create(formData.value).then(() => {
          ElMessage.success("新增成功");
          getTreeData();
          handleCloseDialog();
          handleQuery();
        });
      }
    }
  });
}

function unbindDevEvent(row) {
  console.log("接触绑定", row);
  unbindform.value.id = row.id;
  ElMessageBox.confirm("是否要解除设备绑定?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      UserAPI.unbind(unbindform.value)
        .then(() => {
          ElMessage.success("解绑成功");
          getVehList();
        })
        .finally(() => {
          loading.value = false;
        });
    },
    () => {
      // ElMessage.info("已取消删除");
    }
  );
}

// 删除菜单
function handleDelete(userId: string) {
  if (!userId) {
    ElMessage.warning("请勾选删除项");
    return false;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      UserAPI.deleteByIds(userId)
        .then(() => {
          ElMessage.success("删除成功");
          handleQuery();
          getTreeData();
        })
        .finally(() => {
          loading.value = false;
        });
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

function resetForm() {
  menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();
  ((pUserName.value = ""),
    (formData.value = {
      id: undefined,
      name: "",
      userName: "",
      passWord: "888888",
      userType: 1,
      userCode: "",
      sort: 0,
      status: true,
      remark: "",
      userPid: undefined,
      sysUserContacts: [
        {
          id: undefined,
          contact: "",
          contactNumber: "",
          contactEmail: "",
          userId: undefined,
        },
      ],
    }));
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}
watch(userNameQueryValue, (val) => {
  userNameRef.value!.filter(val);
});
onMounted(() => {
  getTreeData();
});
</script>

<style lang="scss" scoped>
// 用户管理布局样式
.user-layout {
  display: flex;
  // height: 100%;
  height: 760px;
  gap: 15px;
}

.tree-container {
  width: 280px;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  border: 1px solid #e9ecef;
  display: flex;
  flex-direction: column;
  height: 100%;

  .tree-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e9ecef;
    flex-shrink: 0;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #3060ff;
    }
  }

  .user-tree {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    max-height: calc(100% - 80px);
    padding-right: 5px;

    // 隐藏滚动条但保持滚动功能
    scrollbar-width: none;
    /* Firefox */
    -ms-overflow-style: none;
    /* IE and Edge */

    &::-webkit-scrollbar {
      display: none;
      /* Chrome, Safari and Opera */
    }

    :deep(.el-tree-node__content) {
      height: 28px;
      border-radius: 6px;
      margin-bottom: 2px;
      transition: all 0.3s ease;

      &:hover {
        height: 28px;
        background-color: rgba(48, 96, 255, 0.1);
      }
    }

    :deep(.el-tree-node.is-current > .el-tree-node__content) {
      background-color: #3060ff;
      color: white;
      height: 36px;

      .tree-count {
        color: rgba(255, 255, 255, 0.8);
      }
    }

    .tree-node {
      display: flex;
      align-items: center;
      width: 100%;
      padding: 0 10px;

      .tree-icon {
        margin-right: 8px;
        font-size: 14px;
      }

      .tree-label {
        flex: 1;
        font-size: 14px;
      }

      .tree-count {
        font-size: 12px;
        color: #999;
        margin-left: 8px;
      }
    }
  }
}

.content-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .breadcrumb-container {
    margin-bottom: 15px;
    padding: 10px 0;
    border-bottom: 1px solid #e9ecef;

    :deep(.el-breadcrumb__item) {
      font-size: 14px;
    }
  }

  .search-container {
    margin-bottom: 15px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #e9ecef;

    .search-form {
      margin: 0;

      :deep(.el-form-item) {
        margin-bottom: 0;
        margin-right: 20px;
      }
    }
  }

  .action-container {
    margin-bottom: 5px;
    display: flex;
    gap: 10px;
  }

  .table-container {
    flex: 1;
    overflow: hidden;
    // border: 1px solid #e9ecef;
    // border-radius: 8px;

    :deep(.el-table) {
      height: 100%;
    }
  }
}

// 保留原有的其他样式
:deep(.el-dialog__title) {
  color: #000;
}

:deep(.el-form-item--label-right .el-form-item__label) {
  font-weight: bold;
}

.moreBtn {
  padding: 5px 10px;
  border: #d8d4d4 1px solid;
  border-radius: 5px;
}

.moreBtn:hover {
  background-color: #f2f3f5;
}

.selectBox {
  position: absolute;
  background-color: #fff;
  border: #d8d4d4 1px solid;
  border-radius: 5px;
  padding: 10px 30px;
  z-index: 99;
  right: 0;
  top: 35px;
  width: 430px;
}
</style>
